package com.gotrade.springbootexceptiondemo.model;

import com.gotrade.springbootexceptiondemo.common.enums.ResultCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;

/**
 * @author jason.tang
 * @create 2019/4/28
 * @description API数据统一返回类
 */
@ApiModel(description = "API请求的回复信息类")
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    @ApiModelProperty(value = "状态码", example = "ok", position = 1)
    private String code;
    @ApiModelProperty(value = "状态消息", example = "success", position = 2)
    private String message;
    @ApiModelProperty(value = "回复实体数据", position = 3)
    private T data;

    private void setResult(ResultCode resultCode) {
        this.code = resultCode.code();
        this.message = resultCode.msg();
    }

    /**
     *  请求成功，只返回成功状态
     * @param <T>
     * @return
     */
    public static <T> Result<T> success() {
        Result<T> result = new Result<T>();
        result.setResult(ResultCode.SUCCESS);
        return result;
    }

    /**
     * 请求成功，返回数据信息
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<T>();
        result.setResult(ResultCode.SUCCESS);
        result.setData(data);
        return result;
    }

    /**
     * 返回错误信息
     * @param resultCode
     * @param <T>
     * @return
     */
    public static <T> Result<T> failure(ResultCode resultCode) {
        Result<T> result = new Result<T>();
        result.setResult(resultCode);
        return result;
    }

    /**
     * 返回错误信息和数据信息
     * @param resultCode
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> failure(ResultCode resultCode, T data) {
        Result<T> result = new Result<T>();
        result.setResult(resultCode);
        result.setData(data);
        return result;
    }
}
